package com.wbf.demo.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wbf.demo.security.exception.ErrorMsg;
import com.wbf.demo.util.ServletTool;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 返回json格式的无权限信息
 * 定义 403 处理器
 * @author wbf
 *
 */
public class JsonAccessDeniedHandler implements AccessDeniedHandler {
    private final ObjectMapper objectMapper;
    private final ErrorMsg unauthenticatedMsg;

    public JsonAccessDeniedHandler(ObjectMapper objectMapper, ErrorMsg unauthenticatedMsg){
        this.objectMapper = objectMapper;
        this.unauthenticatedMsg = unauthenticatedMsg;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        ServletTool.writeJSONStr(response, objectMapper.writeValueAsString(unauthenticatedMsg));
    }
}
